﻿using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Piedone.ContentTemplates.Models;

namespace Piedone.ContentTemplates.Drivers
{
    public class TemplatePartDriver : ContentPartDriver<TemplatePart>
    {
        protected override string Prefix { get { return "TemplatePart"; } }


        protected override DriverResult Display(TemplatePart part, string displayType, dynamic shapeHelper)
        {
            return ContentShape("Parts_Template_SummaryAdmin",
                () => shapeHelper.Parts_Template_SummaryAdmin());
        }

        // GET
        protected override DriverResult Editor(TemplatePart part, dynamic shapeHelper)
        {
            // Should only run if the item is a new one
            if (part.ContentItem.Id != 0) return null;

            return Combined(
                ContentShape("Parts_Template_Edit",
                    () => shapeHelper.EditorTemplate(
                        TemplateName: "Parts.Template",
                        Model: part,
                        Prefix: Prefix)),
                ContentShape("Parts_Template_SaveButton_Edit",
                    () => shapeHelper.EditorTemplate(
                        TemplateName: "Parts.Template.SaveButton",
                        Model: part,
                        Prefix: Prefix))
                );
        }

        // POST
        protected override DriverResult Editor(TemplatePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }

        protected override void Exporting(TemplatePart part, ExportContentContext context)
        {
            var element = context.Element(part.PartDefinition.Name);

            element.SetAttributeValue("IsTemplate", part.IsTemplate);
            element.SetAttributeValue("TemplateId", part.TemplateId);
        }

        protected override void Importing(TemplatePart part, ImportContentContext context)
        {
            var partName = part.PartDefinition.Name;

            context.ImportAttribute(partName, "IsTemplate", value => part.IsTemplate = bool.Parse(value));
            context.ImportAttribute(partName, "TemplateId", value => part.TemplateId = int.Parse(value));
        }
    }
}